package org.jprogger.myworld.api.secure;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jprogger.myworld.api.request.ApiRequest;

public class ApiRequestSigner {
	
	public static ApiRequest signRequest(ApiRequest apiRequest, String secretKey) throws SignRequestException {
		
		if (apiRequest != null && secretKey != null) 
		{
			SortedMap<String, Object> params = new TreeMap<String, Object>();
			params.putAll(apiRequest.getApiRequestParams().getParameterMap());
				
			try 
			{
				String signature = DigestUtils.makeDigest(params, secretKey);
				apiRequest.getApiRequestParams().getParameterMap().put("sig", signature);
				apiRequest.setSignature(signature);
			} 
			catch (NoSuchAlgorithmException nae) 
			{
				throw new SignRequestException(nae);
			} 
			catch (UnsupportedEncodingException uce) 
			{
				throw new SignRequestException(uce);
			}
		}
		else 
		{
			throw new SignRequestException();
		}
		
		return apiRequest;
	}

}
